package io.gitee.tuo_tuo.jfinaldevassistance.validator;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.log.Log;
import io.gitee.tuo_tuo.jfinaldevassistance.common.Rst;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Method;

/**
 * 类名称：ubap
 * 描述: 字段校验拦截器
 * 		jfinal validate @link http://www.jfinal.com/doc/10-1
 * 	    ps: jfinal做的不好，自己重做
 * 版权: Copyright (c) 2018
 * 公司:
 * 作者: tuotuo
 * 版本: 1.0
 * 创建日期: 2018/5/10
 * 创建时间: 20:58
 */
public class ValidatorInterceptor implements Interceptor {

	private static final Log log = Log.getLog(ValidatorInterceptor.class);
	@Override
	public void intercept(Invocation inv) {
		Controller controller = inv.getController();
		Method method = inv.getMethod();
		RequiredContainer annotationContainer = method.getAnnotation(RequiredContainer.class);
		if(annotationContainer != null){
			Required[] requireds = annotationContainer.value();
			for(Required required : requireds){
				boolean result = validateRequired(controller, required);
				if(result == false){
					return;
				}
			}
		}else{
			Required required = method.getAnnotation(Required.class);
			if(required != null){
				boolean result = validateRequired(controller, required);
				if(result == false){
					return;
				}
			}
		}
		inv.invoke();
	}

	private boolean validateRequired(Controller controller, Required required){
		String key = required.k();
		String para = controller.getPara(key);
		if(StringUtils.isBlank(para)){
			String msg = required.msg();
			controller.renderJson(Rst.fail().setMsg(msg));
			return false;
		}
		return true;
	}
}
